var pageBean = null;
var dataList = {};
var provinces = {};
var cities = {};
var spaces = {};
var productTypes = {};
var processPersons = {};
var salesPersons = {};
var sourceOfChannels = {};
var currentData = null;
var extensions = {};
var clientClassifications = {};
var currentSelectOrder = {};
var contracttemplate = {};

$(document).ready(function(e) {	
	
	$('#newClueFollow').click(function(){ //打开添加跟进记录窗口
        $('.theme-popover-mask').fadeIn(100);  
        $('#clueFollowForm').slideDown(200);  
        clearClueFollowForm();
    })  
    $('#closeClueFollow').click(closeClueFollow);//添加跟进记录窗口右上角的关闭
	$('#btnCancleClueFollow').click(closeClueFollow);//添加跟进记录窗口下面的取消按钮
	$('#btnSaveClueFollow').click(saveClueFollow);//添加跟进记录下的确定按钮
    
    $('#newOrder').click(function(){ //打开添加订单窗口
        $('.theme-popover-mask').fadeIn(100);  
        $('#orderForm').slideDown(200);  
        $('#btnSaveOrder').unbind();
        $('#btnSaveOrder').click(saveOrder);//添加订单窗口下确定按钮
        console.log(JSON.stringify(currentData));
        if(currentData != null){
        	var mClient = currentData['client'];
        	var provinceId = $("#formProvince").val();
        	var cityId =  $("#formCity").val();
        	var spaceId = $("#formSpace").val();
        	var processPersonId = $("select[name='processPerson'][formparameter='clue']").val(); 
        	if($.trim(processPersonId) == ''){
        		if(currentData["processPerson"] != null){
        			processPersonId = currentData.processPerson.id;
        		}else{
        			processPersonId = localStorage.getItem('salsePerson');
        		}        		
        	}
        	$("select[name='salesPerson'][formparameter='order']").val(processPersonId).trigger('change');        	
        	$("SELECT[name='cityId'][formParameter='order']").unbind();
        	$("SELECT[name='cityId'][formParameter='order']").val(cityId).trigger('change');        	
        	$('#salesTimeaaa1').val(laydate.now(0, 'YYYY-MM-DD'));
        	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='order']");	
        	$(spaceIdSelect).empty();
        	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
        	if(cityId == '0'){
        		$.each(spaces,function(key,space){	
        			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
        		});
        	}else{
        		$.each(spaces,function(key,space){	
        			if(cityId == space.city.cityId){
        				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
        			}
        		});
        	}
        	$(spaceIdSelect).val(spaceId).trigger('change');
        	$("SELECT[name='cityId'][formParameter='order']").change(cityIdOrderChange);
        	$("[name='orderName'][formParameter='order']").val(''); 
        	$("[name='description'][formParameter='order']").val(''); 
        }
    });
    $('#closeOrder').click(closeOrder);//添加订单窗口右上角的关闭
    $('#btnCancleOrder').click(closeOrder);//添加订单窗口下面的取消按钮
    
  
  
	//切换客户类型输入信息
	$("#formClientType").change(clientTypeChange);	
	$("#btnSave").click(save);//保存客户详情
	$("#btnCancle").click(cancle);//客户详情页面的取消按钮
	
	$("#btnClean").click(clean);//清除搜索按钮
	$("#btnAdd").click(add);//搜索栏里的添加客户订单按钮
	$("#clientExtensions").hide();//默认隐藏企业扩展信息
	
	$("A[name='clientDetail']").click(clientDetail);//客户详情页和客户订单tab切换
	$("A[name='clientOrder']").click(clientOrder);//客户详情页和客户订单tab切换
	
	initialExtensions();//初始化企业扩展信息表单信息
	
	initialClientclassifications();//初始化客户分类信息到页面，供全局查找和使用
	initialPlaces();//初始化省份和市选择框
	initialSpace();//加载和初始化空间信息选择
	initialContracttemplate();//初始化合同模板信息
	initialSourceOfChannel();//初始化渠道来源信息
	initialProductType();//初始化产品类型信息
	search(1);
	initialSelect();//初始化页面上的选择框数据
	initialProcessPerson();//加载并初始化领取人以及销售人员的信息
	$("SELECT[name='placeProvinceSelect']").change(provinceChange);	
	$("SELECT[name='provinceId']").change(provinceIdChange);
	$("SELECT[name='placeCitySelect']").change(cityChange);
	$("SELECT[name='cityId'][formParameter='clue']").change(cityIdChange);//客户详情页的线索信息中的市选择框变化事件
	$("SELECT[name='cityId'][formParameter='order']").change(cityIdOrderChange);//添加客户订单弹出框中的市选择变化事件
	
	$("input[type='file'][name='file']").change(uploadSpaceImage);//合同页上传PDF
	
	initailContract();//合同控制初始化
});

function closeClueFollow(){//关闭跟进记录弹出窗口
	 $('.theme-popover-mask').fadeOut(100);  
     $('#clueFollowForm').slideUp(200);  
}

function clearClueFollowForm(){	
	$("[formParameter='clueFollow']").each(function(index,element){
		try{
			var name = $(element).attr("name");	
			if("clientClassification" == name){
				var firstVal = $(element).find('option').eq(0).val();				
				$(element).val(firstVal).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function saveClueFollow(){//保存跟进记录
	var clueFollow = {};
	$("[formParameter='clueFollow']").each(function(index,element){
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				clueFollow = false;
				return false;
			}
			if("clientClassification" == name){
				clueFollow[name] = clientClassifications[val];
			}else{
				clueFollow[name] = val;
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	if(currentData != null){
		clueFollow["clueId"] = currentData["id"];
		clueFollow["orderId"] = currentData["theDetailOrderId"];
		//console.log("order_info:"+JSON.stringify(currentData));
	}
	if(clueFollow != false){
		$.ajax({
	        url: '/euc/clue/addfollow',
	        data:JSON.stringify(clueFollow),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType:'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	try{
	        		clueFollow = result.data; 
	        		var newFollowIndex = -1;
	        		$.each(currentData["clueFollowList"],function(index,follow){
	        			if(follow.id == clueFollow.id){
	        				newFollowIndex = index;
	        				return false;
	        			}else{
	        				newFollowIndex = index+1;
	        			}
	        		});
	        		if(newFollowIndex == -1){
	        			currentData["clueFollowList"]= [];
	        			currentData.clueFollowList[0] = clueFollow;
	        		}else{
	        			currentData.clueFollowList[newFollowIndex] = clueFollow;
	        		}
	        		setForm(currentData);
		        	closeClueFollow();
		        	clearClueFollowForm();
	        	}catch(e){
	        		console.log(e.message);
	        	}
	        },
	        error: function () {
	        	console.log(e.message);
	        }  
	    });
	}
}

function closeOrder(){//闭关添加订单弹出窗口
	 $('.theme-popover-mask').fadeOut(100);  
     $('#orderForm').slideUp(200);  
}

function getOrder(order){//获取添加订单弹出窗口上的数据
	if(order == null){
		order = {};
	}
	$("[formParameter='order']").each(function(index,element){
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				order = false;
				return false;
			}
			if("cityId" == name){
				order[name] = val;
				order["provinceId"] = cities[val].provinceId;
			}else if("salesPerson" == name){
				order[name] = salesPersons[val];
			}else{
				order[name] = val;
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	if(currentData != null){
		var client = currentData["client"];
		console.log(JSON.stringify(client));
		client = JSON.stringify(client);
		client = $.parseJSON(client);
		client["orderList"] = [];
		console.log(JSON.stringify(client));
		order["client"] = client;
	}
	return order;
}

function setOrder(order){//编辑订单时，将选中的订单数据初始化到订单弹出窗口
	if(order == null){
		return;
	}
	$("[formParameter='order']").each(function(index,element){
		try{					
			var name = $(element).attr("name");	
			$(element).val(order[name]);
			if("cityId" == name){
				$("select[name='"+name+"']").val(order[name]).trigger('change');				
			}else if("salesPerson" == name){
				$("select[name='"+name+"']").val(order[name].id).trigger('change');
			}else if("spaceId" == name){
				$("select[name='"+name+"']").val(order[name]).trigger('change');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function updateOrder(newOrder){//更新订单数据到数据库
	if(newOrder == null){
		return;
	}
	newOrder = getOrder(newOrder);
	if(newOrder == false){
		return;
	}
	$.ajax({
        url: '/euc/order/update',
        data:JSON.stringify(newOrder),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );

        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		newOrder = result.data;         		
        		var newOrderIndex = -1;
        		$.each(currentData.client.orderList,function(index,order){
        			if(newOrder.id == order.id){
        				newOrderIndex = index;
        				return false;
        			}else{
        				newOrderIndex = index+1;
        			}
        		});
        		if(newOrderIndex == -1){
        			currentData.client["orderList"]= [];
        			currentData.client.orderList[0] = newOrder;
        		}else{
        			currentData.client.orderList[newOrderIndex] = newOrder;
        		}
        		setForm(currentData);
        		closeOrder();
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/order/update error");
        }  
    });
	
}

function saveOrder(){//添加新订单到数据库
	var newOrder = {};
	newOrder = getOrder(newOrder);
	if(newOrder == false){
		return;
	}
	$.ajax({
        url: '/euc/order/add',
        data:JSON.stringify(newOrder),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		newOrder = result.data;         		
        		var newOrderIndex = -1;
        		$.each(currentData.client.orderList,function(index,order){
        			if(newOrder.id == order.id){
        				newOrderIndex = index;
        				return false;
        			}else{
        				newOrderIndex = index+1;
        			}
        		});
        		if(newOrderIndex == -1){
        			currentData.client["orderList"]= [];
        			currentData.client.orderList[0] = newOrder;
        		}else{
        			currentData.client.orderList[newOrderIndex] = newOrder;
        		}
        		setForm(currentData);
        		closeOrder();
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/order/add error");
        }  
    });
}


function clientDetail(){//显示客户详情tab
	$("A[name='clientDetail']").addClass("selected");
	$("A[name='clientOrder']").removeClass("selected");
	$("#tab1").show();
	$("#tab2").hide();
}

function clientOrder(){//显示客户订单tab
	$("A[name='clientDetail']").removeClass("selected");
	$("A[name='clientOrder']").addClass("selected");
	$("#tab1").hide();
	$("#tab2").show();
}

function initialExtensions(){//初始化企业扩展信息字段表单
	$.ajax({
        url: '/euc/extension/list',
        data:'',//JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	//alert(JSON.stringify(result));
	        var extensionDiv = $("#clientExtensions");
	        $(extensionDiv).empty();
	        $('<div class="formtitle "><span>企业扩展信息</span></div>').appendTo($(extensionDiv));	        
	    	$.each(result,function(i,data){
	    		var html = '';
	    		if(data.id==1){//指定所属行业
    				html += '<ul class="forminfo"  clientType="企业"><li><label >所属行业</label>';
    				html += '<select extensionId = "1" name="extension1" class="incinput"  message="请选择所属行业" formParameter="extension" >';
    				html += '<option value="请选择" selected="selected">请选择</option>';
					html += '<option value="互联网科技">互联网科技</option>';
					html += '<option value="贸易">贸易</option>';
					html += '<option value="金融">金融</option>';
					html += '<option value="电商平台">电商平台</option>';
					html += '<option value="企业服务">企业服务</option>';
					html += '<option value="软件开发">软件开发</option>';
					html += '<option value="品牌设计">品牌设计</option>';
					html += '<option value="营销推广">营销推广</option>';
					html += '<option value="影视动漫">影视动漫</option>';
					html += '<option value="其他">其他</option>';
    				html += '</select> </li> </ul>';
    			}else{
		    		if(data.contentLength <= 50){
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="incinput" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else if(data.contentLength <= 100){
		    			html += '<ul class="forminfo" clientType="企业">';
		    			html += '<li><label>'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><input required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><input '; 
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" type="text" class="indinput" style="width:677px;" ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '" /></li></ul>'; 
		    		}else{
		    			html += '<ul class="forminfo"  clientType="企业">';
		    			html += '<li><label >'+data.extensionName;
		    			if(data.required == '是'){
		    				html += '<b>*</b></label><textarea  required = "1" message="请输入' + data.extensionName + '" ';
		    			}else{
		    				html += '</label><textarea  ';
		    			}
		    			html += '  extensionId = "' + data.id + '" ';
		    			html += '  name="extension'+data.id+'" cols="" rows="" class="langtext"  ';
		    			html += '  formParameter="extension" placeholder= "请输入' + data.extensionName + '"></textarea></li></ul>'; 
		    		}
    			}
	    		$(extensionDiv).append(html);
	    		extensions[data.id] = data;
			});
	    	if(result.length > 0){
	    		$("#clientExtensions").show();
	    	}
        },
        error: function () {
        	console.log("/euc/extension/list error");
        }  
    });
}

function initialProcessPerson(){//初始化领取人以及销售人员表数据
	
	var requestJson = {functionId:'1120'};
	$.ajax({
        url: '/euc/user/functionusers',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	var salesPersonSelect = $("SELECT[name='salesPerson']");
        	$.each(result,function(i,data){
        		var style = '';
        		var style = '';
        		if(data.enable == 'false' || data.enable == false){
        			style = 'style="color:red;"';
        		}
        		$('<option ' + style + ' value="'+ data.id +'">'+ data.name +'</option>').appendTo($(salesPersonSelect));
        		processPersons[data.id] = data;
        		salesPersons[data.id] = data;
			});
        },
        error: function () {
        	console.log("/euc/user/functionusers error");
        }  
    });
	
}


function clean(){//请空搜索条件
	var citiesSelect = $("SELECT[name='placeCitySelect']");           		
	$.each(cities,function(key,city){	
   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
	});
	$(citiesSelect).val(0).trigger('change');
	
	var spaceSelect = $("SELECT[name='spaceSelect']");
	$.each(spaces,function(key,space){	
   		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
	});
	$(spaceSelect).val(0).trigger('change');
	$("INPUT[name='parameter']").val('');
	$('input[name="orderTimeStart"]').val('');
	$('input[name="orderTimeEnd"]').val('');
}

function initialSelect(){//初始化页面上的选择框数据
	
	var provinceSelect = $("SELECT[name='placeProvinceSelect']");
	var provinceIdSelect = $("SELECT[name='provinceId']");
	$.each(provinces, function(key, province) {//key provinceId,val province json object
		$('<option value="'+ key +'">'+ province.provinceName +'</option>').appendTo($(provinceSelect));
		$('<option value="'+ key +'">'+ province.provinceName +'</option>').appendTo($(provinceIdSelect));
	});
	
	var citiesSelect = $("SELECT[name='placeCitySelect']");  
	var cityIdClueSelect = $("SELECT[name='cityId'][formParameter='clue']");
	var cityIdOrderSelect = $("SELECT[name='cityId'][formParameter='order']");
	$.each(cities,function(key,city){	
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(cityIdClueSelect));
   		$('<option value="'+ key +'">'+ city.cityName +'</option>').appendTo($(cityIdOrderSelect));
	});
	
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	var spaceIdClueSelect = $("SELECT[name='spaceId'][formParameter='clue']");
	var spaceIdOrderSelect = $("SELECT[name='spaceId'][formParameter='order']");
	$.each(spaces,function(key,space){	
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceIdClueSelect));
   		$('<option value="'+ key +'">'+ space.spaceName +'</option>').appendTo($(spaceIdOrderSelect));
	});
	$(spaceSelect).val(0).trigger('change');
	$(spaceIdClueSelect).val(0).trigger('change');
	$(spaceIdOrderSelect).val(0).trigger('change');
	
	var sourceChannelIdSelect = $("SELECT[name='sourceChannelId']");	
	$.each(sourceOfChannels,function(key,sourceOfChannel){	
   		$('<option value="'+ key +'">'+ sourceOfChannel.sourceOfChannelName +'</option>').appendTo($(sourceChannelIdSelect));
	});
	$(sourceChannelIdSelect).val(0).trigger('change');
	
	
	var productTypeIdSelect = $("SELECT[name='productTypeId']");	
	$.each(productTypes,function(key,productType){	
   		$('<option value="'+ key +'">'+ productType.productTypeName +'</option>').appendTo($(productTypeIdSelect));
	});
	$(productTypeIdSelect).val(0).trigger('change');
	
	
	//初始化客户分类选择框
	var clientClassificationSelect = $("SELECT[name='clientClassification']");
	$(clientClassificationSelect).empty();
	$.each(clientClassifications, function(key, clientClassification) {//key provinceId,val province json object
		if(clientClassification.clientLevel != null){
			$('<option value="'+ key +'">'+ clientClassification.clientLevel.clientLevelName + "-" + clientClassification.clientClassificationName +'</option>').appendTo($(clientClassificationSelect));
		}
	});
	var firstVal = $(clientClassificationSelect).find('option').eq(0).val();				
	$(clientClassificationSelect).val(firstVal).trigger('change');
}

function cityChange(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceSelect = $("SELECT[name='spaceSelect']");	
	$(spaceSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));   		
		});	
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceSelect));
			}	   		
		});
	}
	$(spaceSelect).val(0).trigger('change');
}

function cityIdChange(){
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='clue']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
		});
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
			}	   		
		});
	}
	$(spaceIdSelect).val(0).trigger('change');
}

function cityIdOrderChange(){//订单弹出窗口市选择变化处理方法
	var cityIdSelected=$(this).children('option:selected').val();
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='order']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));	
	if(cityIdSelected == '0'){
		$.each(spaces,function(key,space){	
			$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));   		
		});
	}else{
		$.each(spaces,function(key,space){	
			if(cityIdSelected == space.city.cityId){
				$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
			}	   		
		});
	}
	$(spaceIdSelect).val(0).trigger('change');
}

function provinceChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var citiesSelect = $("SELECT[name='placeCitySelect']");
	$(citiesSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(citiesSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(citiesSelect));
		});
	}else{
		$.each(cities,function(key,city){	
	   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(citiesSelect));
		});
	}
	$(citiesSelect).val(0).trigger('change');
}

function provinceIdChange(){
	var provinceIdSelected=$(this).children('option:selected').val();
	var cityIdSelect = $("SELECT[name='cityId'][formParameter='clue']");
	$(cityIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(cityIdSelect));
	if(provinceIdSelected != '0'){			
		var province = provinces[provinceIdSelected];
		$.each(province.cities,function(index,data){	
       		$('<option value="'+ data.cityId +'">'+ data.cityName +'</option>').appendTo($(cityIdSelect));
		});
	}else{
		$.each(cities,function(key,city){	
	   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(cityIdSelect));
		});
	}
	$(cityIdSelect).val(0).trigger('change');
}

function initialClientclassifications(){//加载客户分类数据
	try{
		var clientClassificationString = localStorage.getItem('clientClassification');
		clientClassifications = $.parseJSON(clientClassificationString);
	}catch(e){
		console.log(e.messge);
	}
}

function initialPlaces(){//加载省市数据信息
	try{
		var provinceString = localStorage.getItem('province');
		var cityString = localStorage.getItem('city');
		provinces = $.parseJSON(provinceString);
		cities = $.parseJSON(cityString);
	}catch(e){
		console.log(e.messge);
	}
}

function initialContracttemplate(){//合同模板信息
	try{
		var contracttemplateString = localStorage.getItem('contracttemplate');
		contracttemplates = $.parseJSON(contracttemplateString);
	}catch(e){
		console.log(e.messge);
	}
}


function initialSpace(){//初始化空间信息
	try{
		var spaceString = localStorage.getItem('space');
		spaces = $.parseJSON(spaceString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/space',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		spaces[data.id] = data;  
	   			});
	        	var spaceJson = JSON.stringify(spaces);
	        	localStorage.setItem('space',spaceJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function initialSourceOfChannel(){//初始化渠道来源信息
	try{
		var sourceOfChannelString = localStorage.getItem('sourceOfChannel');
		sourceOfChannels = $.parseJSON(sourceOfChannelString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/sourceofchannel',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		sourceOfChannels[data.id] = data;  
	   			});
	        	var sourceOfChannelJson = JSON.stringify(sourceOfChannels);
	        	localStorage.setItem('sourceOfChannel',sourceOfChannelJson);
        	}catch(e){
        		console.log(e.messge);
        	}
        },
        error: function () {
        	console.log('/euc/system/sourceofchannel error');
        }  
    });
}

function initialProductType(){//初始化产品类型信息
	try{
		var productTypeString = localStorage.getItem('productType');
		productTypes = $.parseJSON(productTypeString);
	}catch(e){
		console.log(e.messge);
	}
	$.ajax({
        url: '/euc/system/producttype',
        data:'',
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
	        	$.each(result,function(index,data){	
	        		productTypes[data.id] = data;  
	   			});
	        	var productTypeJson = JSON.stringify(productTypes);
	        	localStorage.setItem('productType',productTypeJson);
        	}catch(e){
        		/*alert(e.message);*/
        	}
        },
        error: function () {
        	/*alert("error");*/
        }  
    });
}

function clientTypeChange(){//切换客户类型输入信息
	var clientType = $(this).children('option:selected').val();
	$("[clientType]").hide();
	$("[clientType='"+ clientType +"']").show();	
}

function getClueJson(clue){//获取客户详情页的表单数据，构造参数
	$("[formParameter='clue']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var val =  $(element).val();
			if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
				var message = $(element).attr("message");
				alert(message);
				clue = false;
				return false;
			}
			
			clue[name] = val;
			
		}catch(e){
			console.log(e.messge);
		}
	});
	if(clue != false){
		try{
			//clue['processPerson'] = processPersons[$("SELECT[name='processPerson']").val()];
		}catch(e){
			console.log(e.messge);
		}
		
		var client = clue['client'];
		try{
			if(client == null){
				client = {};
			}
			$("[formParameter='client']").each(function(index,element){		
				var name = $(element).attr("name");	
				client[name] = $.trim($(element).val());
			});
			clue['client'] = client;
		}catch(e){
			console.log(e.messge);
		}
		
		var clientExtensionList = client['clientExtensionList'];
		try{			
			if(clientExtensionList == null){
				clientExtensionList = [];
			}
			var clientType = client["clientType"];
			$("[formParameter='extension'][name^='extension']").each(function(index,element){
				if("企业" == clientType){
					var required = $(element).prop("required");
					var val =  $(element).val();
					if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
						var message = $(element).attr("message");
						alert(message);
						clue = false;
						return false;
					}
				}
				if($(element).val() == '请选择'&&"企业" == clientType){
					alert("请选择所属行业");return false;
				}
				var extensionId = $(element).attr("extensionId");
				var clientExtension = null;
				var index = -1;
				$.each(clientExtensionList,function(i,data){
					if(data.extensionId == extensionId){
						index = i;
						clientExtension = data;
					}
				});
				if(null == clientExtension){
					clientExtension = {};
				}
				clientExtension['extensionId'] = extensionId;
				clientExtension['extension'] = $(element).val();
				if(-1 == index){
					clientExtensionList[clientExtensionList.length] = clientExtension;					
				}else{
					clientExtensionList[index] = clientExtension;
				}
			});
			client['clientExtensionList'] = clientExtensionList;
		}catch(e){
			console.log(e.message);
		}
		if(false != clue){
			clue['client'] = client;
		}		
	}
	return clue;
}


function save(){//添加客户信息，因签约客户没有添加客户功能，所以此方法无用，暂留
	currentData = {};
	currentData = getClueJson(currentData);
	if(currentData == false){
		return false;
	}
	$.ajax({
        url: '/euc/clue/add',
        data:JSON.stringify(currentData),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	if(datas.status == 0){        		
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	currentData = null;
            	search(pageBean.currentPage);            	
        	}else{
        		alert(datas.message);
        	}
        },
        error: function () {
        	console.log('/euc/clue/add error');
        }
    });
}

function update(currentData){//更新客户信息到数据库
	if(currentData == null){
		return false;
	}
	currentData = getClueJson(currentData);
	if(currentData == false){
		return false;
	}
	$.ajax({
        url: '/euc/clue/update',
        data:JSON.stringify(currentData),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (datas, textStatus, response) {
        	if(datas.status == 0){        		
        		$("DIV[name='dataList']").show();
            	$("DIV[name='dataForm']").hide();
            	currentData = null;
            	search(pageBean.currentPage);            	
        	}else{
        		alert(datas.message);
        	}
        },
        error: function () {
        	/*alert("error");*/
        }
    });
}

function cancle(){//客户详情页的取消按钮，显示订单信息列表
	$("DIV[name='dataList']").show();
	$("DIV[name='dataForm']").hide();
}

function clearForm(){//清除客户信息表单数据
	
	var provinceIdSelect = $("SELECT[name='provinceId']");  
	$(provinceIdSelect).val(0).trigger('change');
	
	var cityIdSelect = $("SELECT[name='cityId'][formParameter='clue']");  
	$(cityIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(cityIdSelect));
	$.each(cities,function(key,city){	
   		$('<option value="'+ city.cityId +'">'+ city.cityName +'</option>').appendTo($(cityIdSelect));
	});
	$(cityIdSelect).val(0).trigger('change');
	
	var spaceIdSelect = $("SELECT[name='spaceId'][formParameter='clue']");	
	$(spaceIdSelect).empty();
	$('<option value="0" selected>请选择</option>').appendTo($(spaceIdSelect));
	$.each(spaces,function(key,space){	
   		$('<option value="'+ space.id +'">'+ space.spaceName +'</option>').appendTo($(spaceIdSelect));
	});
	$(spaceIdSelect).val(0).trigger('change');
	
	$("[formParameter]").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			if(tagName == 'SELECT'){
				var firstVal = $(element).find('option').eq(0).val();				
				$(element).val(firstVal).trigger('change');
			}else{
				$(element).val('');
			}
		}catch(e){
			console.log(e.messge);
		}
	});
}

function setForm(clue){//编辑时，初始化客户信息表单
	var orderId = clue['theDetailOrderId'];
	$("[formParameter='clue']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				$(element).val(clue[name]).trigger('change');
			}else{
				$(element).val(clue[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	try{
		$("SELECT[name='provinceId']").val(clue['provinceId']).trigger('change');
		$("SELECT[name='cityId'][formParameter='clue']").val(clue['cityId']).trigger('change');
		$("SELECT[name='spaceId'][formParameter='clue']").val(clue['spaceId']).trigger('change');
		$("SELECT[name='processPerson']").val(clue['processPerson'].id).trigger('change');
	}catch(e){
		console.log(e.messge);
	}
	
	var client = clue['client'];
	$("[formParameter='client']").each(function(index,element){		
		try{
			var tagName = $(element).prop("tagName");
			var name = $(element).attr("name");
			if(tagName == 'SELECT'){
				$(element).val(client[name]).trigger('change');
			}else{
				$(element).val(client[name]);
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	
	try{
		$.each(client.clientExtensionList,function(i,data){
			$("[formParameter='extension'][name='extension"+data.extensionId+"']").val(data.extension);
		});
	}catch(e){
		console.log(e.message);
	}

	try{//设置跟进记录
		var clueFollowTable = $("#clueFollowTable");
		$(clueFollowTable).empty();
		$.each(clue.clueFollowList,function(i,clueFollow){
			//if(orderId != undefined && orderId != null && orderId !='' && clueFollow.orderId == orderId){
                var bgcolor= localStorage.getItem('trcolor');
                if(i % 2 == 0){
                    bgcolor = '';
                }
                var html = '<tr '+ bgcolor +'>';
                html += '<td>' + clueFollow.visitTime + '</td>';
                html += '<td>' + clueFollow.contact + '</td>';
                html += '<td>' + clueFollow.contactNumber + '</td>';
                html += '<td>' + clueFollow.clientClassification.clientLevel.clientLevelName + '-' + clueFollow.clientClassification.clientClassificationName + '</td>';
                html += '<td>' + clueFollow.followUser.name + '</td>';
                html += '<td>' + clueFollow.followContent + '</td>';
                html += '</tr>';
                $(clueFollowTable).append(html);
			//}
		});
	}catch(e){
		console.log(e.message);
	}
	
	
	var orderDetails = $("#orderDetailDiv");
	$(orderDetails).empty();
	try{//订单数据
		var aaa ='中华人民共和国';
		$("#noOrderDiv").show();
		$.each(clue.client.orderList,function(i,order){
			$("#noOrderDiv").hide();
			var cityName = cities[order.cityId].cityName;
			var spaceName = spaces[order.spaceId].spaceName;			
	    	var html = 	'<div class="incForm" >';
	    	html +=  '      <div class="formtitle ">';
	    	html +=  '            <span>NO.</span>';
	    	html +=  '          <span class="iceFormTitleSpan nob" ">'+ (i+1) +'</span>';
	    	html +=  '      </div>';
	    	html +=  '      <div class="formtitle-left ">';
	    	html +=  '         <ul class="forminfo">';
	    	html +=  '             <li><label >订单编号：</label><span class="iceFormInfoSpan" ">'+ order.orderNumber +'</span></li>';
	    	html +=  '                <li><label >订单名称：</label><span class="iceFormInfoSpan" ">'+ order.orderName +'</span></li>';
	    	html +=  '                <li><label >城市：</label><span class="iceFormInfoSpan" ">'+ cityName +'</span></li>';
	    	html +=  '                <li><label >房间总数：</label><span class="iceFormInfoSpan" ">'+ order.roomCount +'</span></li>';
	    	html +=  '               <li><label >已回款金额：</label><span class="iceFormInfoSpan" ">'+ order.payAmount +'</span></li>';
	    	html +=  '               <li><label >入驻日期：</label><span class="iceFormInfoSpan" ">'+ order.enterTime +'</span></li>';
	    	html +=  '               <li><label >销售日期：</label><span class="iceFormInfoSpan" ">'+ order.salesTime +'</span></li>';
	    	html +=  '            </ul>';
	    	html +=  '        </div>';
	    	html +=  '       <div class="formtitle-right">';
	    	html +=  '            <ul class="forminfo">';
	    	html +=  '              <li><label >合同总数：</label><span class="iceFormInfoSpan" ">'+ order.contractCount +'</span></li>';
	    	html +=  '                <li><label >订单类型：</label><span class="iceFormInfoSpan" ">'+ order.orderType +'</span></li>';
	    	html +=  '              <li><label >空间：</label><span class="iceFormInfoSpan" ">'+ spaceName +'</span></li>';
	    	html +=  '             <li><label >订单总金额：</label><span class="iceFormInfoSpan" ">'+ order.orderAmount +'</span></li>';
	    	html +=  '               <li><label >未回款金额：</label><span class="iceFormInfoSpan" ">'+ order.noPayAmount +'</span></li>';
	    	html +=  '              <li><label >离场时间：</label><span class="iceFormInfoSpan" ">'+ order.leaveTime +'</span></li>';
	    	html +=  '              <li><label >销售人员：</label><span class="iceFormInfoSpan" ">'+ order.salesPerson.name +'</span></li>';
	    	html +=  '           </ul>';
	    	html +=  '       </div>';
	    	html +=  '        <div class="lingqu" style="margin-left: 190px;margin-top: 20px;" >';
	    	html +=  '           <input name="btnOrderDetialLook"  type="button" orderId="'+ order.id +'" class="btn close" value="查看"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    	if(order.contractCount == 0){	    		
	    		html +=  '         <input name="btnOrderEdit"  type="button" orderId="'+ order.id +'"  class="btn close" value="编辑"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	    		html +=  '         <input name="btnOrderDelete"  type="button" orderId="'+ order.id +'"  class="btn close" value="删除"/>';
	    	}
	    	html +=  '       </div>';
	    	html +=  '   </div>';
        	$(orderDetails).append(html);
		});
		$("input[type='button'][name='btnOrderDetialLook']").click(orderDetail);
		$("input[type='button'][name='btnOrderEdit']").click(orderEdit);
		$("input[type='button'][name='btnOrderDelete']").click(orderDelete);
	}catch(e){
		console.log(e.message);
	}
	
}

function orderEdit(){	//订单编辑
	try{
		var currentOrder = null;
		var id = $(this).attr("orderId");
		$.each(currentData.client.orderList,function(index,order){
			if(order.id == id){
				currentOrder = order;
				return false;
			}
		});
		if(currentOrder != null){
			setOrder(currentOrder);
			$('.theme-popover-mask').fadeIn(100);  
	        $('#orderForm').slideDown(200);  
	        $('#btnSaveOrder').unbind();
			$('#btnSaveOrder').click(function(){
				updateOrder(currentOrder);
			});//添加订单窗口下确定按钮		
		}		
	}catch(e){
		console.log(e.message);
	}
}

function orderDelete(){//删除订单
	if(confirm("确定删除该记录?")){
		var id = $(this).attr("orderId");
		var requestJson = {id:id};
		$.ajax({
	        url: '/euc/order/delete',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType: 'JSON',
	        async: true,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	if(result.status == 0){	        		
	        		var orderList = [];
	        		var arrayIndex = 0;
	        		$.each(currentData.client.orderList,function(index,order){
	        			if(order.id != id){
	        				orderList[arrayIndex] = order;
	        				arrayIndex++;
	        			}
	        		});
	        		currentData.client.orderList = orderList;
	        		setForm(currentData);
	        	}else{
	        		alert(result.message);
	        	}	        	
	        },
	        error: function () {
	        	console.log("error");
	        }  
	    });
	 }
}

function add(){//添加订单按钮
	clearForm();
	$("#newOrderDiv").show();
	$("#btnNewOrderNext").unbind();
	$("#btnNewOrderNext").click(newOrderNext);
	$("#btnNewOrderCancle").unbind();
	$("#btnNewOrderCancle").click(newOrderCancle);	
	$("DIV[name='dataList']").hide();
}

function newOrderNext(){//添加订单页，输入客户名之后，点击下一步，调用此方法
	try{
		var newOrderClientName = $.trim($("input[name='newOrderClientName']").val());
		if(newOrderClientName == ''){
			alert("请输入客户名称！");
			return ;
		}
		var requestJson = {"clientName":newOrderClientName};
		$.ajax({
	        url: '/euc/client/signclientbyname',
	        data:JSON.stringify(requestJson),
	        beforeSend: function(request) {
	        	var accessToken = localStorage.getItem('accessToken');
	            request.setRequestHeader("accessToken",accessToken );
	        },
	        dataType:'JSON',
	        async: false,
	        contentType:'application/json;charset=utf-8',
	        type: 'POST',
	        success: function (result, textStatus, response) {
	        	try{
	        		$.each(result,function(index,data){
	        			dataList[data.id] = data;
	        		});
	        	}catch(e){
	        		console.log(e.message);
	        	}
	        },
	        error: function () {
	        	console.log(e.message);
	        }  
	  });
		var clientId = null;
		
		$.each(dataList,function(key,clue){//key为clue的id
			var client = clue["client"];
			console.log(JSON.stringify(client));
			if(client != null){
				if(client.clientType == '个人'){
					if(client.memberName.indexOf(newOrderClientName) >= 0){
						clientId = key;
					}
				}else if(client.clientType == '企业'){
					if(client.companyName.indexOf(newOrderClientName) >= 0){
						clientId = key;
					}
				}
			}
		});
		if(clientId != null){
			$("#newOrderDiv").hide();
			detail(clientId,null);
			$("A[name='clientOrder']").trigger("click");
			$("#newOrder").trigger("click");
		}else{
			alert("未搜索到对应客户！");
		}
	}catch(e){
		console.log(e.message);
	}
}

function newOrderCancle(){//取消息添加订单
	$("#newOrderDiv").hide();
	$("DIV[name='dataList']").show();
}
function initPayment(){
	$("#paymentCount").html('<option value="1" selected>1</option>');
	for(var i=2;i<36;i++){
		$("#paymentCount").append('<option value="'+i+'">'+i+'</option>');
	}
}
function detail(id,theId){//编辑客户信息
	currentData = dataList[id];
	$("#clueFollowTable").html('');
	clearForm();
	if(theId != null)
		currentData['theDetailOrderId'] = theId;
	setForm(currentData);
	initPayment();
	$("#operator").html("编辑");
	$("DIV[name='dataList']").hide();
	$("DIV[name='dataForm']").show();
	$("#clueFollowDiv").show();
	$("#usualDitail").show();
	$("#btnSave").unbind();
	$("#btnSave").click(function(){
		update(currentData);
	});
	
	var orderId = $.trim(localStorage.getItem('orderId'));
	if(orderId != ''){
		$("#tabclientOrder").trigger('click');
		$("input[name='btnOrderDetialLook'][orderid='"+orderId+"']").trigger('click');
		localStorage.removeItem('orderId');
	}
}


function initailPageNumber(totalPage,currentPage,pageLength){
	try{
			var midNumber = Math.ceil((pageLength-2)/2);
			var paginList = $(".paginList");
			$(paginList).empty();			
			var prev = '<li class="paginItem"><a href="javascript:;"><span class="pagepre"></span></a></li>';
			var next = '<li class="paginItem"><a href="javascript:;"><span class="pagenxt"></span></a></li>';
			if( totalPage <= pageLength - 2){
				$(prev).appendTo($(".paginList"));
				for(var i = 1; i<totalPage+1; i++){
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
					if(i == currentPage){
						pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
					}			
					$(pagenItem).appendTo($(".paginList"));
				}
				$(next).appendTo($(".paginList"));
			}else{				
				if(currentPage <= midNumber){
					$(prev).appendTo($(".paginList"));
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+i+'</a></li>';
						if(i == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+i+'</a></li>';
						}			
						$(pagenItem).appendTo($(".paginList"));
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}if(totalPage - currentPage < midNumber){

					var index = totalPage;
					for(var i=1;i <= pageLength - 4;i++){
						var pagenItem = '<li class="paginItem"><a href="javascript:;">'+index+'</a></li>';
						if(index == currentPage){
							pagenItem = '<li class="paginItem current"><a href="javascript:;">'+index+'</a></li>';
						}			
						$(pagenItem).prependTo($(".paginList"));
						index--;
					}		
					var pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					var pagenItem = '<li class="paginItem"><a href="javascript:;">'+ 1 +'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					$(next).appendTo($(".paginList"));
				}else if(totalPage - currentPage >= midNumber && currentPage > midNumber){

					pagenItem = '<li class="paginItem current"><a href="javascript:;">'+currentPage+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					var count = midNumber - 3;
					for(var i = 1; i<=count;i++){
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage-i)+'</a></li>';
						$(pagenItem).prependTo($(".paginList"));
						pagenItem = '<li class="paginItem"><a href="javascript:;">'+ (currentPage+i)+'</a></li>';
						$(pagenItem).appendTo($(".paginList"));
					}
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).prependTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+1	+'</a></li>';
					$(pagenItem).prependTo($(".paginList"));
					$(prev).prependTo($(".paginList"));
					
					pagenItem = '<li class="paginItem more"><a href="javascript:;">...</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					pagenItem = '<li class="paginItem"><a href="javascript:;">'+totalPage+'</a></li>';
					$(pagenItem).appendTo($(".paginList"));	
					$(next).appendTo($(".paginList"));
				}				
			}
			$(".paginItem").click(function(){
				if($(this).hasClass("more")){
					//alert("more");
					return;
				}else if($(this).find(".pagepre").length > 0){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur > 1){
						search(cur - 1);
					}
				}else if($(this).find(".pagenxt").length > 0 ){
					var cur = $('.paginItem.current').find("a").html();
					cur = parseInt(cur);
					if(cur < totalPage){
						search(cur + 1);
					}
				}else{
					var cur = $(this).find("a").html();
					cur = parseInt(cur);
					search(cur);
				}
			});
	}catch(e){/*alert(e.messge);*/}	
}

function getSearchParameter(currentPage){
	try{
		var orderId = $.trim(localStorage.getItem('orderId'));
		var clientName = $.trim(localStorage.getItem('clientName'));
		if(clientName != ''){
			$("INPUT[name='parameter']").val(clientName);
		}
		var parameter = $("INPUT[name='parameter']").val();
		var cityId = $("#searchCity").val();
		var spaceId = $("#searchSpace").val();
		if(cityId == '0'){
			cityId = '';
		}	
		if(spaceId == '0'){
			spaceId = '';
		}
		var orderTimeStart = $("INPUT[name='orderTimeStart']").val();
		var orderTimeEnd = $("INPUT[name='orderTimeEnd']").val();
		
		var requestJson = {currentPage:currentPage,data:{like:{"client.companyName":parameter,'client.memberName':parameter},equals:{'enable':true,'cityId':cityId,'spaceId':spaceId,'orderTimeStart':orderTimeStart,'orderTimeEnd':orderTimeEnd,"orderId":orderId}}};
		localStorage.removeItem('clientName');
		console.log(JSON.stringify(requestJson));
		return requestJson;
	}catch(e){
		console.log(e.messge);
	}
	return false;	
}

function search(currentPage){
	var requestJson = getSearchParameter(currentPage);
	if(requestJson == false){
		return false;
	}
	$.ajax({
        url: '/euc/client/signclient',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	console.log(JSON.stringify(result));
        	pageBean = result.data;
        	$("#userTable").empty();
        	var rowNumber = 0;
        	var temp = 0;
        	var orderByNumber = 1 ;
        	while(orderByNumber <= pageBean.list.length){
        		$.each(result.data.list,function(i,data){
        			$.each(data.client.orderList,function(index,order){
        				if(orderByNumber == order.orderByNumber){
        					orderByNumber = orderByNumber + 1;
        					console.log(order.orderByNumber);
		            		var clientType = '';
		            		var clientName = '';
		            		if(data['client'] != null){
		            			clientType = $.trim(data['client'].clientType);
		            			if(clientType == '个人'){
		            				clientName = $.trim(data['client'].memberName);
		            			}else{
		            				clientName = $.trim(data['client'].companyName);
		            			}
		            			if(clientName == ''){
		            				clientName = $.trim(data['contact']);
		            			}
		            		}        		
		            		var spaceName = '';
		            		if($.trim(data["spaceId"]) != ''){
		            			try{
		            				console.log(JSON.stringify(spaces));
		            				if(spaces == null){
		            					initialSpace();
		            				}
		            				spaceName =$.trim(spaces[data["spaceId"]].spaceName);
		            			}catch(e){
		            				console.log(e.message);
		            			}
		            		}
		            		
		            		var sourceOfChannelName = '';
		            		if($.trim(data["sourceChannelId"]) != ''){
		            			sourceOfChannelName =$.trim(sourceOfChannels[data["sourceChannelId"]].sourceOfChannelName);
		            		}

            		
            			
            				var bgcolor= localStorage.getItem('trcolor');
                    		if(rowNumber % 2 == 0){
                    			bgcolor = '';
                    		}
                    		rowNumber++;
                    		var roomName = '';
                    		$.each(order.contractList,function(i,contract){
                    			$.each(contract.contractProductList,function(j,product){
                    				if(roomName == ''){
                    					roomName = product.roomName;
                    				}else{
                    					roomName += ','+product.roomName;
                    				}
                    				
                    			});            			
                    		});
                    		
                    		
                    		var html = '<tr '+ bgcolor +'>';
                    		html += '<td>' + clientName + '</td>';
                    		html += '<td>' + cities[data.cityId].cityName + '</td>';
                    		html += '<td>' + spaceName + '</td>';
                    		html += '<td>' + roomName + '</td>';
                    		html += '<td>' + order.orderAmount + '</td>';  
                    		html += '<td>' + order.payAmount + '</td>';
                    		html += '<td>' + order.noPayAmount + '</td>';
                    		html += '<td>' + sourceOfChannelName + '</td>';
                    		html += '<td>' + order.salesPerson.name + '</td>';
                    		html += '<td>' + order.salesTime + '</td>';
                    		html += '<td>' + order.createTime + '</td>';
                    		html += '<td><a id="order'+order.id+'" clueid="'+data.id+'" href="javascript:detail('+data.id+','+order.id+');" class="tablelink">编辑</a>&nbsp;&nbsp;&nbsp;</td>';
                    		html += '</tr>';
            	        	$("#userTable").append(html);
            			}        			
            		});
    	        	dataList[data.id] = data;
    			});
        	}
    		var orderId = $.trim(localStorage.getItem('orderId'));
    		if(orderId != ''){
    			var clueId = $("#order"+orderId).attr('clueid');
    			detail(clueId,null);
    		}
    		
        	$("#totalRow").html(pageBean.totalRow+'&nbsp;');
        	$("#currentPage").html(pageBean.currentPage+'&nbsp;');
        	$("#pageSize").html(pageBean.pageSize+'&nbsp;');        	
        	var pageLength = 15;
        	initailPageNumber(pageBean.totalPage,pageBean.currentPage,pageLength);        	
        },
        error: function () {
        	console.log('/euc/client/signclient error');
        }
    });
}


function setContract(order){
	try{
		var contractListTable = $("#contractListTable");
		$(contractListTable).empty();
		$.each(order.contractList,function(index,contract){			
			var html = '<tr>';
			html += '<td>'+$.trim(contract.contractType)+'</td>';
			html += '<td>'+$.trim(contract.contractAmount)+'</td>';
			html += '<td>'+$.trim(contract.roomCount)+'</td>';
			html += '<td>'+$.trim(contract.averagePrice)+'</td>';
			html += '<td>'+$.trim(contract.contractStartTime)+'</td>';
			html += '<td>'+$.trim(contract.contractEndTime)+'</td>';
			html += '<td>'+$.trim(order.salesPerson.name)+'</td>';
			html += '<td>'+$.trim(contract.createUser.name)+'</td>';
			html += '<td><a href="javascript:setContractForm('+contract.id+');" class="tablelink">查看</a></td>';
			html += '</tr>';			
			$(contractListTable).append(html);
		});
	
		
		var contractHirePurchaseListTable = $("#contractHirePurchaseListTable");		
		$(contractHirePurchaseListTable).empty();
		$.each(order.contractList,function(index,contract){	
			var rows = 1;
			try{
				if(contract.contractHirePurchaseList != null){
					rows = contract.contractHirePurchaseList.length;
				}
			}catch(e){
				console.log(e.message);
			}
			$.each(contract.contractHirePurchaseList,function(index,contractHirePurchase){
					var html = '<tr>';
					if(index == 0){
						html += '<td align="center" valign="middle" rowspan="'+rows+'">'+$.trim(contract.contractType)+'<br/>'+contract.contractStartTime +'至'+contract.contractEndTime+'</td>';	
					}					
					var hirePurchaseNumber = $.trim(contractHirePurchase.hirePurchaseNumber);
					var hirePurchaseDiscript = "";
					if(hirePurchaseNumber == '0'){
						hirePurchaseDiscript = '押金';
					}else{
						hirePurchaseDiscript = '第'+hirePurchaseNumber+'期服务费';	
					}
					html += '<td align="center" valign="middle" >'+hirePurchaseDiscript+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseStart)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseEnd)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.bill_Date)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseAmount)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.realPaymentAmount)+'</td>';
					html += '<td>'+$.trim(contractHirePurchase.hirePurchaseStatus)+'</td>';
					html += '</tr>';						
					$(contractHirePurchaseListTable).append(html);					
			});	
		});	
		
		
	}catch(e){
		console.log(e.message);	
	}	
}

function orderDetail(){//查看订单
	try{
		currentSelectOrder = null;
		var id = $(this).attr("orderId");
		$.each(currentData.client.orderList,function(index,order){
			if(order.id == id){
				currentSelectOrder = order;
				return false;
			}
		});			
		console.log(JSON.stringify(currentSelectOrder));
		setContract(currentSelectOrder);
		if(currentSelectOrder != null){
			$("DIV[name='dataForm']").hide();
			$("#oneOrderDetailDiv").show();
			$(window).scrollTop(0);
			//$("#oneOrderDetailDivContent").show();	
			var orderDetail = $("#oneOrderDetailDivContent");
			$(orderDetail).empty();
			try{//订单数据
					var cityName = cities[currentSelectOrder.cityId].cityName;
					var spaceName = spaces[currentSelectOrder.spaceId].spaceName;	
					var clientName = '';
      		if(currentData['client'] != null){
      			clientType = $.trim(currentData['client'].clientType);
      			if(clientType == '个人'){
      				clientName = $.trim(currentData['client'].memberName);
      			}else{
      				clientName = $.trim(currentData['client'].companyName);
      			}
      			if(clientName == ''){
      				clientName = $.trim(data['contact']);
      			}
      		}
		    	var html = 	'<div class="incForm" >';
		    	html +=  '      <div class="formtitle ">';
		    	html +=  '            <span>订单详情</span>';
		    	html +=  '      </div>';
		    	html +=  '      <div class="formtitle-left ">';
		    	html +=  '         <ul class="forminfo">';
		    	html +=  '             <li><label >订单编号：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.orderNumber +'</span></li>';
		    	html +=  '                <li><label >订单名称：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.orderName +'</span></li>';
		    	html +=  '                <li><label >城市：</label><span class="iceFormInfoSpan" ">'+ cityName +'</span></li>';
		    	html +=  '                <li><label >当前房间总数：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.roomCount +'</span></li>';
		    	html +=  '               <li><label >已回款金额：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.payAmount +'</span></li>';
		    	html +=  '               <li><label >入驻日期：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.enterTime +'</span></li>';
		    	html +=  '               <li><label >销售日期：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.salesTime +'</span></li>';
		    	html +=  '            </ul>';
		    	html +=  '        </div>';
		    	html +=  '       <div class="formtitle-right">';
		    	html +=  '            <ul class="forminfo">';
		    	html +=  '              <li><label >客户名称：</label><span class="iceFormInfoSpan" ">'+ clientName +'</span></li>';
		    	html +=  '              <li><label >订单类型：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.orderType +'</span></li>';
		    	html +=  '              <li><label >空间：</label><span class="iceFormInfoSpan" ">'+ spaceName +'</span></li>';
		    	html +=  '              <li><label >订单总金额：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.orderAmount +'</span></li>';
		    	html +=  '              <li><label >未回款金额：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.noPayAmount +'</span></li>';
		    	html +=  '              <li><label >离场时间：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.leaveTime +'</span></li>';
		    	html +=  '              <li><label >销售人员：</label><span class="iceFormInfoSpan" ">'+ currentSelectOrder.salesPerson.name +'</span></li>';
		    	html +=  '           </ul>';
		    	html +=  '       </div>';
		    	html +=  '   </div>';
					$(orderDetail).append(html);
					$("#newContract").attr("orderId",currentSelectOrder.id);
			}catch(e){
				console.log(e.message);
			}
		}		
	}catch(e){
		console.log(e.message);
	}
}


function initailContract(){
	
	$("#backClientOrder").click(backClientOrder);
	$("#newContract").click(selectContractType);
	$("#btnSelectContractType").click(showContractForm);
	$("#btnCancleContractType").click(closeSelectContractType);
	$("#closeContractType").click(closeSelectContractType);
	$("#btnSaveContractDetail").click(saveContractDetail);
	$("#btnCancleContractDetail").click(cancleContractDetail);		
	$("#addContractProduct").click(addContractProduct);
	$("#btnSaveContractProduct").click(saveContractProduct);
	$("#btnCancleContractProduct").click(closeContractProductForm);
	$("#closeContractProductForm").click(closeContractProductForm);
	$("#addRoomAsContractProduct").click(addRoomAsContractProduct);
}

function addContractProduct(){//打开合同产品表单并添加合同产品
	 $('.theme-popover-mask').fadeIn(100);  
	 $('#addContractProductForm').slideDown(200);	 
	 var contractStartTime = $("[formparameter='contract'][name='contractStartTime'").val();
	 var contractEndTime = $("[formparameter='contract'][name='contractEndTime'").val();	 
	 $("[formparameter='contractProduct'][name='rentStart'").val(contractStartTime);
	 $("[formparameter='contractProduct'][name='rentEnd'").val(contractEndTime);
}

function closeContractProductForm(){//关闭合同产品表单
  $('.theme-popover-mask').fadeOut(100);  
  $('#addContractProductForm').slideUp(200);  

}

function saveContractProduct(){//保存合同产品表单数据
	var product = $.trim($("#contractProductFormTable").html());
	console.log(product);
	if(product != ''){
		closeContractProductForm();
	}else{
		alert('请先添加工位产品！');
	}	
}


function selectContractType(){//选择合同类型	 
   	$('.theme-popover-mask').fadeIn(100);  
	  $('#newContractDiv').slideDown(200);  //新建合同前选择合同类型，入驻合同，退租合同
}

function closeSelectContractType(){
	$('.theme-popover-mask').fadeOut(100);  
  $('#newContractDiv').slideUp(200);  
}

function initialContractForm(){
	if(currentData != null){
		var mClient = currentData.client;
		if(mClient != null){
			try{
				console.log(JSON.stringify(mClient));
				if(mClient.clientType == "个人"){
					$("input[formparameter='contract'][name='partyAName']").val(mClient.memberName);
					$("input[formparameter='contract'][name='partyAAddress']").val(mClient.memberAddress);
				}else if(mClient.clientType == '企业'){
					$("input[formparameter='contract'][name='partyAName']").val(mClient.companyName);
					$("input[formparameter='contract'][name='partyAAddress']").val(mClient.companyAddress);
				}
				$("input[formparameter='contract'][name='partyAContact']").val(currentData.contact);
				$("input[formparameter='contract'][name='partyAContactNumber']").val(currentData.contactNumber);
				$("input[formparameter='contract'][name='partyAEmail']").val(currentData.email);
			}catch(e){
				console.log(e.message);
			}
		}
		//初始化合同模板
		try{
			var spaceId = $.trim(currentData.spaceId);
			if(spaceId != '' && contracttemplates != null){
				$.each(contracttemplates,function(key,data){
					if(currentContractType == '入驻合同'){
						$("#top_menu_title").html("新建入驻合同");
						if(data.contractType == 1 && data.spaceId == spaceId){
							$("input[formparameter='contract'][name='partyBName']").val(data.partyBName);
							$("input[formparameter='contract'][name='partyBAddress']").val(data.partyBAddress);
							$("input[formparameter='contract'][name='partyBContact']").val(data.partyBContact);
							$("input[formparameter='contract'][name='partyBContactNumber']").val(data.partyBContactNumber);
							$("input[formparameter='contract'][name='partyBEmail']").val(data.partyBEmail);
							return false;
						}
					}else if(currentContractType == '退租合同'){
						if(data.contractType == 2 && data.spaceId == spaceId){
							$("#top_menu_title").html("新建退租合同");
							$("input[formparameter='contract'][name='partyBName']").val(data.partyBName);
							$("input[formparameter='contract'][name='partyBAddress']").val(data.partyBAddress);
							$("input[formparameter='contract'][name='partyBContact']").val(data.partyBContact);
							$("input[formparameter='contract'][name='partyBContactNumber']").val(data.partyBContactNumber);
							$("input[formparameter='contract'][name='partyBEmail']").val(data.partyBEmail);
							return false;
						}
					}
				});
			}
		}catch(e){
			console.log(e.message);
		}
	}
}

function showContractForm(){
	
	 var contractType = $("SELECT[name='contractTypeSelect']").val();
   if($.trim(contractType) != ''){
	   	currentContractType = $("SELECT[name='contractTypeSelect']").val();
	   	$('.theme-popover-mask').fadeIn(100);  
	   	$('#newContractDiv').slideDown(200);  //新建合同前选择合同类型，入驻合同，退租合同	
	   	$("#btnSaveContractDetail").unbind();
		$("#btnSaveContractDetail").click(saveContractDetail);
		selectContractProduct = [];
		clearContractForm();
		initialContractForm();
   }else{
   		alert("请选择合同类型");	
   		return;
   }
	$("[contracttype][contracttype!='"+ currentContractType +"']").hide();
    $("[contracttype][contracttype='"+ currentContractType +"']").show();
	closeSelectContractType();	
	$("#oneOrderDetailDiv").hide();
	$("#contractDetailDiv").show();	
}  

function cancleContractDetail(){//取消合同操作
	selectContractProduct = [];
	$.each(cacheContractProducts,function(index,data){
		selectContractProduct[index] = data;
	});
	currentContract["contractProductList"] = selectContractProduct;
	closeContractDetail();
}

function closeContractDetail(){//关闭合同页面
	$("#oneOrderDetailDiv").show();
	$("#contractDetailDiv").hide();
}


function getContract(contract){
	if(contract == null){
		contract = {};	
	}
	
	$("[formParameter='contract']").each(function(index,element){		
		try{			
			var required = $(element).prop("required");				
			var name = $(element).attr("name");	
			var myContractType = $(element).attr("contracttype");
			var val =  $(element).val();
			if(currentContractType == $.trim(myContractType)){
					if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
						var message = $(element).attr("message");
						alert(message);
						contract = false;
						return false;
					}
			}		
			contract[name] = val;
		}catch(e){
			console.log(e.messge);
		}
	});
	console.log(JSON.stringify(selectContractProduct));
	currentContract["contractProductList"] =	selectContractProduct;
	if(currentSelectOrder != null && $.trim(contract["order"]) == ''){
		var myOrder = $.parseJSON(JSON.stringify(currentSelectOrder));
		myOrder["contractList"] = null;
		contract["order"] = myOrder;
	}
	try{
//		取消限制
//		if(contract['contractProductList'] == null || contract['contractProductList'].length == 0){
//			if(contract['contractType'] ==  '入驻合同' ){
//				alert('请添加合同产品！');
//				return false;
//			}		
//		}
	}catch(e){
		console.log(e.message);
	}
	return contract;
}

function saveContractDetail(){//保存合同
	$("#btnSaveContractDetail").unbind();
	currentContract = {};
	currentContract = getContract(currentContract);
	currentContract["contractType"] = currentContractType;
	currentContract["contractProductList"] =	selectContractProduct;
	console.log(JSON.stringify(selectContractProduct));
	if(currentContract == false){
		$("#btnSaveContractDetail").click(saveContractDetail);
		return;	
	}
	console.log(JSON.stringify(currentContract));
	$.ajax({
        url: '/euc/contract/add',
        data:JSON.stringify(currentContract),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		currentContract = result.data;
        		var newIndex = -1;
        		$.each(currentSelectOrder.contractList,function(index,contractElement){
        			if(currentContract.id == contractElement.id){
        				newIndex = index;
        				return false;
        			}else{
        				newIndex = index+1;
        			}
        		});
        		if(newIndex == -1){
        			currentSelectOrder.contractList = [];
        			currentSelectOrder.contractList[0] = currentContract;
        		}else{
        			currentSelectOrder.contractList[newIndex] = currentContract;
        		}
        		setContract(currentSelectOrder);
        		setForm(currentData);
				console.log(JSON.stringify(result));
        		closeContractDetail();
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	$("#btnSaveContractDetail").click(saveContractDetail);
        	console.log("/euc/order/add error");
        }  
    });
}


function clearContractForm(){
	$("#contractProductTableOfContract").empty();
	$("#contractProductFormTable").empty();
	$("[formParameter='contract']").each(function(index,element){		
		try{			
			$(element).val('');
		}catch(e){
			console.log(e.messge);
		}
	});
	$("SELECT[formParameter='contract'][name='paymentCount']").val(1).trigger("change");
}



function setContractForm(contractId){
	clearContractForm();
	var myContract = null;
	$.each(currentSelectOrder.contractList,function(index,contractElement){
			if(contractId == contractElement.id){
				myContract = contractElement;
				return false;
			}
  });
  if(myContract == null){
  	return ;	
  }
  
  $("[contracttype][contracttype!='"+ myContract.contractType +"']").hide();
  $("[contracttype][contracttype='"+ myContract.contractType +"']").show();
  
	$("[formParameter='contract']").each(function(index,element){		
		try{			
			var name = $(element).attr("name");
			$(element).val($.trim(myContract[name]));
			if(name == 'filePath'){
				if($.trim(myContract[name]) != ''){
					$("#reviewPDF").attr('href',myContract[name]);
					$("#reviewPDF").show();
				}else{
					$("#reviewPDF").hide();
				}
			}
		}catch(e){
			console.log(e.messge);
		}
	});
	cacheContractProducts = [];
	$.each(myContract.contractProductList,function(index,contractProduct){
		cacheContractProducts[index] = contractProduct;
	});
	setContractProductFormTableList(myContract.contractProductList);
	$("#oneOrderDetailDiv").hide();
	$("#contractDetailDiv").show();	
	$("#btnSaveContractDetail").unbind();
	currentContract = myContract;
	$("#btnSaveContractDetail").click(function(){
		$.each(currentSelectOrder.contractList, function(index,contractElement) {
			if (contractId == contractElement.id) {
				currentContract = contractElement;
				updateContract(currentContract);
				currentContract = contractElement;
				return false;
			}
		});	
	});
}

function updateContract(myContract){
	if(myContract == null){
		return;	
	}
	myContract = getContract(myContract);
	console.log(JSON.stringify(selectContractProduct));
	myContract["contractProductList"] =	selectContractProduct;
	if(myContract == false){
		return;	
	}
	console.log(JSON.stringify(myContract));
	$.ajax({
        url: '/euc/contract/update',
        data:JSON.stringify(myContract),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType:'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		myContract = result.data;
        		var newIndex = -1;
        		$.each(currentSelectOrder.contractList,function(index,contractElement){
        			if(myContract.id == contractElement.id){
        				newIndex = index;
        				return false;
        			}else{
        				newIndex = index+1;
        			}
        		});
        		if(newIndex == -1){
        			currentSelectOrder.contractList = [];
        			currentSelectOrder.contractList[0] = myContract;
        		}else{
        			currentSelectOrder.contractList[newIndex] = myContract;
        		}
        		setContract(currentSelectOrder);
        		setForm(currentData);
				console.log(JSON.stringify(result));
        		closeContractDetail();
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log("/euc/order/add error");
        }  
    });
}


function backClientOrder(){//从合同页面返回客户订单
	$("DIV[name='dataForm']").show();
	$("#oneOrderDetailDiv").hide();	
}

function addRoomAsContractProduct(){
	
	var requestJson = {};
	$('input[formParameter="contractProduct"]').each(function(index,element){
			try{			
					var required = $(element).prop("required");				
					var name = $(element).attr("name");	
					var val =  $(element).val();
					if((required == '1' || required == true)  && ($.trim(val) == '' || $.trim(val) == '0')){				
						var message = $(element).attr("message");
						alert(message);
						requestJson = false;
						return false;
					}
					requestJson[name] = val;
			}catch(e){
				console.log(e.messge);
			}
	});	
	if(requestJson == false){		
		return;
	}	

	var currentOrder = null;
	var orderId = $("#newContract").attr("orderId");
	$.each(currentData.client.orderList,function(index,order){
		if(order.id == orderId){
			currentOrder = order;
			return false;
		}
	});
	if(currentOrder==null || currentOrder.spaceId == undefined){
		requestJson["spaceId"] = 4;
	}else{
		requestJson["spaceId"] = currentOrder.spaceId;	
	}
			
	$.ajax({
        url: '/euc/room/availableroom',
        data:JSON.stringify(requestJson),
        beforeSend: function(request) {
        	var accessToken = localStorage.getItem('accessToken');
            request.setRequestHeader("accessToken",accessToken );
        },
        dataType: 'JSON',
        async: true,
        contentType:'application/json;charset=utf-8',
        type: 'POST',
        success: function (result, textStatus, response) {
        	try{
        		if(result.status == '0'){
        			var contractProduct = {};
        			$.each(result.data,function(index,data){
        				contractProduct["roomId"] = data.id;
        				contractProduct["roomName"] = data.roomName;
        				contractProduct["roomType"] = data.roomType;
        				contractProduct["provinceId"] = data.province.provinceId;
        				contractProduct["cityId"] = data.city.cityId;
        				contractProduct["spaceId"] = data.space.id;
        				contractProduct["roomPrice"] = data.roomPrice;
        				contractProduct["seatCount"] = data.seatCount;
        				contractProduct["enable"] = data.enable;
        				contractProduct["rentStart"] = $('input[formParameter="contractProduct"][name="rentStart"]').val();
        				contractProduct["rentEnd"] = $('input[formParameter="contractProduct"][name="rentEnd"]').val();
								return false;        				
        			}); 
        			var newContractProductIndex = -1;
        			$.each(selectContractProduct,function(index,data){        					
									if(data.roomId == contractProduct.roomId){
										newContractProductIndex = index;
										alert("你已添加房间【"+data.roomName+"】");
										return false;
									}else{
										newContractProductIndex = index+1;
									}
							});	
							if(newContractProductIndex == -1){
								selectContractProduct[0] = contractProduct;  
							}else{
								selectContractProduct[newContractProductIndex] = contractProduct;  	
							}
        		}else{
        			alert(result.message);
        		}
        		setContractProductFormTableList(selectContractProduct);
        	}catch(e){
        		console.log(e.message);
        	}
        },
        error: function () {
        	console.log(e.message);
        }  
  });	
}

var selectContractProduct = [];
var cacheContractProducts = [];
var currentContract = {};
var currentContractType = "";

function setContractProductFormTableList(contractProducts){
	if(contractProducts == null){
		return;	
	}
	console.log(JSON.stringify(selectContractProduct));
	selectContractProduct =	contractProducts;
	console.log(JSON.stringify(selectContractProduct));
	var tableBody = $("#contractProductFormTable");
	var contractProductTableOfContract = $("#contractProductTableOfContract");
	$(tableBody).empty();
	$(contractProductTableOfContract).empty();
	$("input[name='contractStartTime']").attr("disabled",false);
	$("input[name='contractEndTime']").attr("disabled",false);
	var contractStartTime = "";
	var contractEndTime = "";
	$.each(contractProducts,function(index,data){
		if(contractStartTime == '' || contractStartTime > data.rentStart){
			//contractStartTime = data.rentStart;
			//$("input[name='contractStartTime']").val(contractStartTime);
			//$("input[name='contractStartTime']").attr("disabled",true);
		}		
		if(contractEndTime == ''  || contractEndTime < data.rentEnd){
			//contractEndTime = data.rentEnd;
			//$("input[name='contractEndTime']").val(contractEndTime);			
			//$("input[name='contractEndTime']").attr("disabled",true);
		}
		
		var html = '<tr>';
		html += '<td>工位</td>';
		html += '<td>'+data.roomName+'</td>';
		html += '<td>'+data.roomPrice+'</td>';
		html += '<td style="width:100px;"><a href="javascript:deleteSelectContractProduct('+data.roomId+');" class="tablelink">删除</a></td>';
		$(tableBody).append(html);
				
		var html2 = '<tr>';
		html2 += '<td>工位</td>';
		html2 += '<td>'+data.roomName+'</td>';
		html2 += '<td>'+data.roomPrice+'</td>';
		html2 += '<td>'+data.rentStart+'</td>';
		html2 += '<td>'+data.rentEnd+'</td>';
		html2 += '<td style="width:100px;"><a href="javascript:deleteSelectContractProduct('+data.roomId+');" class="tablelink">删除</a></td>';
		$(contractProductTableOfContract).append(html2);
	});	
}

function deleteSelectContractProduct(roomId){
	$.each(selectContractProduct,function(index,data){
			if(data.roomId == roomId){
				selectContractProduct.splice(index,1);	
				return false;
			}
	});	
	setContractProductFormTableList(selectContractProduct);
}


function uploadSpaceImage(){
	var fileName = $("#uploadFile").val();
	
	 var dom = document.getElementById("uploadFile");
	 var fileSize = dom.files[0].size;
	 if (fileSize > 50000000) {
		 alert("上传文件过大,请上传小于50M的文件");
		 $("#uploadFile").val("");
		 return false;
	}
	var fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLocaleLowerCase();
	if (fileType != 'pdf') {
		alert("图片只能上传PDF文件！");
		$("#uploadFile").val("");
		return false;
	}
	
	var accessToken = localStorage.getItem('accessToken');
	$('#contractFileForm').ajaxSubmit({
		dataType : "json",
		headers : {'Access-Control-Allow-Origin':'*',"accessToken":accessToken},
		beforeSubmit : function(request) { 
			//alert("正在上传"); 
		}, 
		success : function(result, textStatus, response) { 
			//alert(JSON.stringify(result));
			$("#spaceImage").prop("src",result.fileUrl);
			$("input[name='filePath']").val(result.fileUrl);
			if($.trim(result.fileUrl) != ''){
				$("#reviewPDF").attr("href",result.fileUrl); 
				$("#reviewPDF").show();
			}else{
				$("#reviewPDF").hide();
			}
			//alert('成功上传！');
		},
		error : function(result) {
			//alert('上传失败！'); 
		} 
	});
}
function checkPrice(e,info) { 
    var re = /^\d+(?=\.{0,1}\d+$|$)/ 
    if (e.value != "") { 
        if (!re.test(e.value)) { 
            alert("请输入正确的"+info+"价格"); 
            e.value = ""; 
            e.focus(); 
        } 
    } 
} 
